//
//  GYLoginViewController.m
//  research
//
//  Created by 章鱼 on 17/3/27.
//  Copyright © 2017年 simon. All rights reserved.
//

#import "GYLoginViewController.h"
#import "IconTextfieldView.h"
#import "GYRegisterViewController.h"
#import "GYHomeViewController.h"
#import "NSString+NSString.h"
#import "GYRootViewController.h"
#import "GYBaseNavViewController.h"
#import "AppDelegate.h"
#import "XZImageTextButton.h"
#import "WXApi.h"
#import "WechatManager.h"
#import "GYForgetViewController.h"
#import "GYDefine.h"

@interface GYLoginViewController (){
    AppDelegate *appdelegate;
}

@property (nonatomic, strong)UIButton *closeButton;
@property (nonatomic, strong)UIImageView *photoView;
@property (nonatomic, strong) IconTextfieldView *phoneNumberView;//手机号码
@property (nonatomic, strong) IconTextfieldView *idenfifyNumberView;//密码
@property (nonatomic, strong) UIButton *forgetPasswordButton;//忘记密码
@property (nonatomic, strong) UIButton *loginButton;//登录
@property (nonatomic, strong) UIButton *registerButton;//注册
@property (nonatomic, strong) UILabel *orLable;
@property (nonatomic, strong) UIView *firstLineView;
@property (nonatomic, strong) UIView *secondLineView;
@property (nonatomic, strong) UIButton *wechatButton;
@property (nonatomic, strong) UIButton *tecentButton;
@property (nonatomic, strong) GYRootViewController *rootCtrl;
@property (nonatomic, strong) GYBaseNavViewController *rootNavCtrl;

@end

@implementation GYLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor orz_globalBackground]];
    [self initLoginView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)initLoginView {
    _closeButton = [[UIButton alloc] init];
    [self.view addSubview:_closeButton];
    [_closeButton setImage:[UIImage imageNamed:@"login_button_close"] forState:UIControlStateNormal];
    [_closeButton setTitleColor:[UIColor orz_mainColor] forState:UIControlStateNormal];
    [_closeButton addTarget:self action:@selector(closeClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _photoView = [[UIImageView alloc] init];
    [self.view addSubview:_photoView];
    _photoView.image = [UIImage imageNamed:@"login_icon_avatar"];
    
    _phoneNumberView = [[IconTextfieldView alloc] init];
    [self.view addSubview:_phoneNumberView];
    _phoneNumberView.icon.image = [UIImage imageNamed:@"login_icon_User-name"];
    _phoneNumberView.textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入用户名" attributes:@{NSForegroundColorAttributeName:[UIColor orz_textWhiteBackground]}];
    
    _idenfifyNumberView = [[IconTextfieldView alloc] init];
    [self.view addSubview:_idenfifyNumberView];
    _idenfifyNumberView.icon.image = [UIImage imageNamed:@"login_icon_Password"];
    _idenfifyNumberView.textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入密码" attributes:@{NSForegroundColorAttributeName:[UIColor orz_textWhiteBackground]}];
    _idenfifyNumberView.textFiled.secureTextEntry = YES;

    
    _forgetPasswordButton = [[UIButton alloc] init];
    [self.view addSubview:_forgetPasswordButton];
    [_forgetPasswordButton setTitleColor:[UIColor colorWithHex:@"323232" alpha:1] forState:UIControlStateNormal];
    [_forgetPasswordButton setTitle:@"忘记密码?" forState:UIControlStateNormal];
    _forgetPasswordButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [_forgetPasswordButton addTarget:self action:@selector(forgetPasswordClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _loginButton = [[UIButton alloc] init];
    [self.view addSubview:_loginButton];
    [_loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _loginButton.backgroundColor = [UIColor orz_mainColor];
    [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
    _loginButton.titleLabel.font = [UIFont systemFontOfSize:14];
    _loginButton.layer.cornerRadius = 4.f;
    _loginButton.layer.masksToBounds = YES;
    [_loginButton addTarget:self action:@selector(startLoginClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _registerButton = [[UIButton alloc] init];
    [self.view addSubview:_registerButton];
    [_registerButton setTitleColor:[UIColor colorWithHex:@"323232" alpha:1] forState:UIControlStateNormal];
    [_registerButton setTitle:@"注册" forState:UIControlStateNormal];
    _registerButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [_registerButton addTarget:self action:@selector(registerClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _orLable = [[UILabel alloc] init];
    [self.view addSubview:_orLable];
    _orLable.text = @"或";
    _orLable.textColor = [UIColor colorWithHex:@"323232" alpha:1];
    _orLable.font = [UIFont systemFontOfSize:14];
    
    _firstLineView = [[UIView alloc] init];
    [self.view addSubview:_firstLineView];
    _firstLineView.backgroundColor = [UIColor colorWithHex:@"d5d7dc" alpha:1];
  
    _secondLineView = [[UIView alloc] init];
    [self.view addSubview:_secondLineView];
    _secondLineView.backgroundColor = [UIColor colorWithHex:@"d5d7dc" alpha:1];
    
    _wechatButton = [[XZImageTextButton alloc] init];
    [self.view addSubview:_wechatButton];
    [_wechatButton setTitle:@"微信登录" forState:UIControlStateNormal];
    [_wechatButton setTitleColor:[UIColor colorWithHex:@"323232" alpha:1] forState:UIControlStateNormal];
    _wechatButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [_wechatButton setBackgroundImage:[UIImage imageNamed:@"login_button_weixin"] forState:UIControlStateNormal];
    [_wechatButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, -70, 0)];
    [_wechatButton addTarget:self action:@selector(wechatLogn:) forControlEvents:UIControlEventTouchUpInside];

    
    _tecentButton = [[UIButton alloc] init];
    [self.view addSubview:_tecentButton];
    [_tecentButton setTitle:@"qq登录" forState:UIControlStateNormal];
    [_tecentButton setTitleColor:[UIColor colorWithHex:@"323232" alpha:1] forState:UIControlStateNormal];
    _tecentButton.titleLabel.font = [UIFont systemFontOfSize:12];
    [_tecentButton setBackgroundImage:[UIImage imageNamed:@"login_button_QQ"] forState:UIControlStateNormal];
    [_tecentButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, -70, 0)];
    [_tecentButton addTarget:self action:@selector(tecentLogn:) forControlEvents:UIControlEventTouchUpInside];
    
    [self setLoginUI];
}

- (void)setLoginUI {

    [_closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(12.f);
        make.top.mas_equalTo(30.f);
        make.size.mas_equalTo(CGSizeMake(50* ADJUST_SCREEN_WIDTH_SCALE, 50*ADJUST_SCREEN_HEIGHT_SCALE));
    }];
    
    [_photoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_closeButton.mas_bottom).offset(45*ADJUST_SCREEN_HEIGHT_SCALE);
        make.centerX.mas_equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(77 * ADJUST_SCREEN_WIDTH_SCALE, 77 *ADJUST_SCREEN_HEIGHT_SCALE));
    }];
    
    [_phoneNumberView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_photoView.mas_bottom).offset(20*ADJUST_SCREEN_HEIGHT_SCALE);
        make.left.mas_equalTo(0.f);
        make.right.mas_equalTo(0.f);
        make.height.mas_equalTo(54.f*ADJUST_SCREEN_HEIGHT_SCALE);
        
    }];
    
    [_idenfifyNumberView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_phoneNumberView.mas_bottom);
        make.left.mas_equalTo(0.f);
        make.right.mas_equalTo(0.f);
        make.height.mas_equalTo(54.f*ADJUST_SCREEN_HEIGHT_SCALE);
        
    }];
    
    [_forgetPasswordButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(_idenfifyNumberView.mas_bottom).offset(12.f*ADJUST_SCREEN_HEIGHT_SCALE);
        make.right.mas_equalTo(-20.f*ADJUST_SCREEN_HEIGHT_SCALE);
        
    }];
    
    [_loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_forgetPasswordButton.mas_bottom).with.offset(20.f*ADJUST_SCREEN_HEIGHT_SCALE);
        make.left.mas_equalTo(12.f);
        make.right.mas_equalTo(-12.f);
        make.height.mas_equalTo(44.f*ADJUST_SCREEN_HEIGHT_SCALE);
        
    }];
    
    [_registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(_loginButton.mas_bottom).offset(20.f);
        make.centerX.mas_equalTo(self.view);
        
    }];
    
    [_orLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_registerButton.mas_bottom).offset(26.f);
        make.centerX.mas_equalTo(self.view);
        
    }];
    
    [_firstLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(_orLable.mas_left).offset(-15.f);
        make.size.mas_equalTo(CGSizeMake(92, .5f));
        make.centerY.mas_equalTo(_orLable.mas_centerY);
    }];
    
    [_secondLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_orLable.mas_right).offset(15.f);
        make.size.mas_equalTo(CGSizeMake(92, .5f));
        make.centerY.mas_equalTo(_orLable.mas_centerY);
    }];

    [_wechatButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_firstLineView.mas_bottom).offset(20.f);
        make.right.mas_equalTo(self.view.mas_right).offset(-(SCREEN_WIDTH/2+26));
        make.size.mas_equalTo(CGSizeMake(50, 50));
    }];
    
    [_tecentButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_firstLineView.mas_bottom).offset(20.f);
        make.left.mas_equalTo(self.view.mas_left).offset((SCREEN_WIDTH/2+26));
        make.size.mas_equalTo(CGSizeMake(50, 50));
    }];
}
#pragma mark - loginaction
- (void)closeClick:(UIButton *)btn {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];

}

- (void)startLoginClick:(UIButton *)btn {
    [_phoneNumberView.textFiled resignFirstResponder];
    [_idenfifyNumberView.textFiled resignFirstResponder];
    
    [[YGHttpManager defaultManager] fetchGetUserLoginWithuserName:_phoneNumberView.textFiled.text password:[NSString md5:_idenfifyNumberView.textFiled.text] success:^(id responseObj) {
        GYCommonModel *commonmodel = [GYCommonModel mj_objectWithKeyValues:responseObj];
        if ([[responseObj objectForKey:@"status"] integerValue] == 0) {
            [VBAlertView showTextHUD:commonmodel.message];
            return ;
        }
        [[GYConfigDBManager defaultManager] setLogin:YES];
        [[GYConfigDBManager defaultManager] setGYToken:[commonmodel.data objectForKey:@"token"]];
        GYUserInfoModel *model = [GYUserInfoModel mj_objectWithKeyValues:[commonmodel.data objectForKey:@"user"]];
        [[GYConfigDBManager defaultManager] setUserInformation:model];
        _rootCtrl = [[GYRootViewController alloc] init];
        _rootNavCtrl = [[GYBaseNavViewController alloc] initWithRootViewController:_rootCtrl];
        [_rootNavCtrl.navigationBar setHidden:YES];
        [AppDelegate shareDelegate].window.rootViewController = _rootNavCtrl;
        [[AppDelegate shareDelegate].window makeKeyAndVisible];
        
    } failure:^(NSError *error) {
        
    }];

}
- (void)forgetPasswordClick:(UIButton *)btn {
    GYForgetViewController *forgetCtrl = [[GYForgetViewController alloc] init];
    forgetCtrl.hidesBottomBarWhenPushed = YES;
    forgetCtrl.tabBarController.tabBar.hidden = YES;
    [self.navigationController pushViewController:forgetCtrl animated:YES];

}
- (void)registerClick:(UIButton *)btn {
    GYRegisterViewController *registerCtrl = [[GYRegisterViewController alloc] init];
    registerCtrl.hidesBottomBarWhenPushed = YES;
    registerCtrl.tabBarController.tabBar.hidden = YES;
    [self.navigationController pushViewController:registerCtrl animated:YES];
}

- (void)tecentLogn:(UIButton *)btn {

    [VBAlertView showTextHUD:@"qq登陆暂未开通"];
}

- (void)wechatLogn:(UIButton *)btn {
    if ([[WechatManager defaultManager] isWeiXinAppInstalled]) {
        SendAuthReq* req =[[SendAuthReq alloc ] init ] ;
        req.scope = @"snsapi_userinfo" ;
        req.state = @"12345" ;
        [WXApi sendReq:req];
        appdelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
        WS(weakSelf);
        appdelegate.startLiveBlock = ^(NSString *code){
            SS(strongSelf);
           // [strongSelf getWeiXinOpenId:code];
            [strongSelf startWechatLogin:code];

        };
    }
}

- (void)startWechatLogin:(NSString *)code {

    [[YGHttpManager defaultManager] fetchGetUserWXLoginWithcode:code success:^(id responseObj) {
        
        GYCommonModel *commonmodel = [GYCommonModel mj_objectWithKeyValues:responseObj];
        
        if (commonmodel.status == 0) {
            [VBAlertView showTextHUD:commonmodel.message];
            return ;
        }
        [[GYConfigDBManager defaultManager] setLogin:YES];
        [[GYConfigDBManager defaultManager] setGYToken:[commonmodel.data objectForKey:@"token"]];
        GYUserInfoModel *model = [GYUserInfoModel mj_objectWithKeyValues:[commonmodel.data objectForKey:@"user"]];
        [[GYConfigDBManager defaultManager] setUserInformation:model];
        _rootCtrl = [[GYRootViewController alloc] init];
        _rootNavCtrl = [[GYBaseNavViewController alloc] initWithRootViewController:_rootCtrl];
        [_rootNavCtrl.navigationBar setHidden:YES];
        [AppDelegate shareDelegate].window.rootViewController = _rootNavCtrl;
        [[AppDelegate shareDelegate].window makeKeyAndVisible];
        
    } failure:^(NSError *error) {
        
    }];
    
}

- (void)getWeiXinOpenId:(NSString *)code{
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",GYWECHATAppID,GYWECHATAppSecret,code];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data){
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSString *openID = dic[@"openid"];
                NSString *accessToken = dic[@"access_token"];
                [self getUserInfoToken:accessToken andOpenid:openID andCode:code];
            }
        });
    });
}

-(void)getUserInfoToken:(NSString *)token andOpenid:(NSString *)openID andCode:(NSString *)code
{
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,openID];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (data) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSLog(@"dic  ==== %@",dic);
                GYUserInfoModel *model = [[GYUserInfoModel alloc] init];
                model.address = [NSString stringWithFormat:@"%@ %@",dic[@"province"],dic[@"city"]];
                model.headimgurl = dic[@"headimgurl"];
                model.gender = dic[@"sex"];
                model.userName = dic[@"nickname"];
                [[GYConfigDBManager defaultManager] setUserInformation:model];

                [self startWechatLogin:code];

            }
             });
         });
}

#pragma mark-设置状态栏的样式
-(UIStatusBarStyle)preferredStatusBarStyle{
    //设置为白色
    return UIStatusBarStyleLightContent;
    //默认为黑色
    //return UIStatusBarStyleDefault;
}

#pragma mark-设置状态栏是否隐藏（否）
-(BOOL)prefersStatusBarHidden{
    return YES;
}




@end
